using System;
using System.Diagnostics;
using System.Web;
using System.Web.Security;

namespace Framework.Library.Components.Security
{
	public class AuthenticateUtility
	{
		public const string MEMBER_PREFIX = "Framework_MEMBER_";

		public static string GetUsername()
		{
			return HttpContext.Current.User.Identity.Name.Replace(MEMBER_PREFIX, string.Empty);
		}

		public static bool IsAuthenticated()
		{
			HttpContext context = HttpContext.Current;
			return
				context.User.Identity.IsAuthenticated && (context.User.Identity.Name.IndexOf(MEMBER_PREFIX) != -1);
		}

		public static void LoginUser(string _username, bool _rememberAccount)
		{
			LogoutUser();
			FormsAuthentication.Initialize();
			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, MEMBER_PREFIX + _username, DateTime.Now, DateTime.Now.AddMinutes(45), _rememberAccount, "", FormsAuthentication.FormsCookiePath);
			Trace.Write(FormsAuthentication.FormsCookiePath + FormsAuthentication.FormsCookieName);
			HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
			HttpContext.Current.Response.SetCookie(cookie);
		}

		public static void LogoutUser()
		{
			HttpContext.Current.Items.Remove("MEMBER_INFO");
			HttpContext.Current.Session.Abandon();
			FormsAuthentication.SignOut();
		}
	}
}